package io.bytes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import io.TestResourcesDirectory;

/**
 * 对象输入输出字节流的演示
 * 
 * @author fidel
 */
public class ObjectDemo {
    public static void main(String[] args) {
        File file = new File(TestResourcesDirectory.PATH + File.separator + "BytesObjectDemo.txt");
        FileInputStream fis;
        ObjectInputStream ois;
        // try-with-resources
        try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(-1);
            // 在此流中写入一个16位的字符
            oos.writeChar(65);
            // 在此流中写入UTF-8修改版格式的字符串
            oos.writeUTF("世界");
            oos.flush();
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            System.out.println("当前正在读取的对象：" + ois.readObject());
            System.out.println("当前正在读取的字符：" + ois.readChar());
            System.out.println("当前正在读取的字符串：" + ois.readUTF());
            ois.close();
            fis.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
